<?php

namespace App\Console\Commands;

use App\Models\DeviceInspector;
use App\Models\Msgs;
use App\Models\Device;
use App\Models\ParkInfo;
use App\Models\DeviceInspectOrder;
use Illuminate\Console\Command;
use Carbon\Carbon;
use DB;

class MsgCollection extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'msg:collect';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '告警统计';

    protected $mobile;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->mobile = env('MOBILE_MSG_PHONE');
    }

    /*
    *  发送短信
    * @exp   $content = $route_res->r_username.",".$route_res->r_user_phone.",".date("Y-m-d H:i:s",$route_res->r_order_start_time).",".$data['start_place']."--".$data['end_place'].",". $route_res->r_car_back_place;
    * @param $tpl string m_driver_rec,m_driver_confirm
    */
    function sendMsg($phone, $arr, $tpl){
        return ;
        if(empty($phone)) return;
        $cont = implode(',', $arr);
        try{
            //手机短信
            $service = app('mobilemsg');
            $resp = $service->send($phone,$cont,$tpl);
        }catch (\Exception $ex){
            return response()->json([
                's' => 0,
                'm' => $ex->getMessage()
            ]);
        }
    }


    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $start = Carbon::yesterday()->timestamp;

        $end = Carbon::today()->timestamp;
        $parks = ParkInfo::whereIn('park_code', config('custom.report_parks'))
            ->select(['park_code', 'parking_name'])
            ->orderBy('sort_by', 'desc')
            ->pluck('parking_name','park_code');
        $res = DB::table('t_arm_device_status')->where("type",5)->whereIn("park_code",config('custom.report_parks'))->get();
        $data = $res->map(function($v) use ($parks) {
            $re = [];
            $jdata = \GuzzleHttp\json_decode($v->status, true);
            $park_name = $parks[$v->park_code]??'';
            if(empty($park_name)) return;
            $exist_data = DB::table("msgs")->where("park_code",$v->park_code)
                ->where("arm_code",$v->arm_code)
                ->where("device_id",$v->device_id)
                ->where("type",1)
                ->where("class",0)
                ->first();
            if($exist_data) return;
            // 判断这个设备是否存在
            $exist_data = DB::table("park_channels")->where("park_code",$v->park_code)
                ->where("arm_code",$v->arm_code)
                ->first();
            if(empty($exist_data)) return;
            $device_info = DB::table('t_park_device')
                ->where("park_code",$v->park_code)
                ->where("arm_code",$v->arm_code)
                ->where("factory",$v->factory)
                ->where("device_id",$v->device_id)
                ->select(["gate_type","device_name"])
                ->first();
            if($jdata['cpu'] > 90){
                $re['message'] = "【设备异常】控制器，CPU使用率超过预警值，设备位置<".$park_name."><".($device_info->device_name??'').">，请及时处理";
            } else if($jdata['disk'] > 90){
                $re['message'] = "【设备异常】控制器，磁盘使用率超过预警值，设备位置<".$park_name."><".($device_info->device_name??'').">，请及时处理";
            } else if($jdata['memory'] >= 90){
                $re['message'] = "【设备异常】控制器，内存使用率超过预警值，设备位置<".$park_name."><".($device_info->device_name??'').">，请及时处理";
            }

            if(empty($re['message'])) return;
            $this->sendMsg($this->mobile,[$re['message']],"remind_new_alarm");
            $re['park_code'] = $v->park_code;
            $re['arm_code'] = $v->arm_code;
            $re['device_id'] = $v->device_id;
            $re['created_at'] = date("Y-m-d H:i:s");
            return $re;
        });
        $data = $data->filter(function($item){
           if(!empty($item)) return $item;
        });
        if(empty($data)) return;
        //存入数据库
        $report = DB::table('msgs')->insert(obj2arr($data));


        // 车位饱和度统计
        $res = ParkInfo::whereIn('park_code', config('custom.report_parks'))
            ->select(
            [
                "park_code",
                \DB::raw('round((space_total-space_empty)/space_total*100,2) as per'),
            ]
        )
            ->pluck('per','park_code');
        $carv = [];
        foreach ($res as $k=>$v) {
            if($v>90){
                $park_name = $parks[$k]??'';
                if(empty($park_name)) continue;
                $exist_data = DB::table("msgs")->where("park_code",$k)
                    ->where("class",2)
                    ->where("type",1)
                    ->first();
                if(!empty($exist_data)) continue;
                $tmp = [];
                $tmp['message'] = "【车位预警】剩余空车位不足10%，车场位置<".$park_name.">，车位使用率即将达到上限".
                    "，请联系相关工作人员处理";
                $tmp['park_code'] = $k;
                $tmp['class'] = 2;
                $tmp['created_at'] = date("Y-m-d H:i:s");
                $carv[] = $tmp;
                $this->sendMsg($this->mobile,[$tmp['message']],"remind_new_alarm");
            }
        }
        //存入数据库
        $report = DB::table('msgs')->insert(obj2arr($carv));


        // 维保告警
        $devices = collect(Device::whereIn("park_code",config('custom.report_parks'))->get());
        $data = $devices->map(function($val) use ($parks) {
            $park_name = $parks[$val->park_code]??'';
            if(empty($park_name)) return;
            $exist_data = DB::table("msgs")->where("park_code",$val->park_code)
                ->where("class",1)
                ->where("type",1)
                ->first();
            if(!empty($exist_data)) return;
            // 查询该设备最近的一条记录
            $lastOrder = DeviceInspectOrder::where(['device_id' => $val->id])->latest('id')->first();
            $lastOrder = empty($lastOrder) ? [] : $lastOrder->toArray();

            // 获取设备类型的维保设置
            $deviceInspectorSetting = DeviceInspector::where([
                'device_type' => $val->type,
                'device_brand' => $val->brand,
                'device_model' => $val->spec
            ])
                ->first();
            $deviceInspectorSetting = empty($deviceInspectorSetting) ? [] : $deviceInspectorSetting->toArray();


            // 计算 剩余天数 是否逾期 下次维护时间 累计使用天数
            if(isset($deviceInspectorSetting['inspect_period'])) {
                $remind_days = $deviceInspectorSetting['inspect_period'] - (
                    empty($lastOrder) ?
                        (int)((time() - strtotime($val->use_time)) / (3600 * 24)) :
                        (int)((time() - strtotime($lastOrder['inspect_date'])) / (3600 * 24))
                    );
            } else {
                $remind_days = 0;
            }
            $device_type = ["142"=>"倒闸","270"=>"识别仪","273"=>"控制器","274"=>"扫码器","275"=>"票箱"];
            $device_name = isset($device_type[$val->type])?$device_type[$val->type]:'';
            if($remind_days < 0) {
                $tmp = [];
                $tmp['message'] = "【维保过期】".$val->name."，维保信息已过期，设备位置<".$park_name."><".$val->name.">，请联系运维人员及时更新维保记录";
                $tmp['park_code'] = $val->park_code;
                $tmp['class'] = 1;
                $tmp['created_at'] = date("Y-m-d H:i:s");
                $this->sendMsg($this->mobile,[$tmp['message']],"remind_new_alarm");
                return $tmp;
            }
        });
        $data = $data->filter(function($item){
            if(!empty($item)) return $item;
        })->toArray();
        if(empty($data)) return;
        //存入数据库
        $report = DB::table('msgs')->insert($data);
        $this->info('告警信息下发统计');
    }


}
